import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/style.dart';
import 'package:yp/widgets/ad_box.dart';
import 'package:yp/widgets/index.dart';

/// 秒杀活动
class SeckillHome extends StatefulWidget {
  const SeckillHome({Key key}) : super(key: key);

  @override
  _SeckillHomeState createState() => _SeckillHomeState();
}

class _SeckillHomeState extends State<SeckillHome>
    with TickerProviderStateMixin {
  var _tabList = [];

  TabController primaryTC;

  int indicatorIndex = 0;

  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init() {
    _tabList = [];
    primaryTC = TabController(length: _tabList?.length ?? 0, vsync: this);
    method().then((value) {}).whenComplete(() {
      if (mounted) {
        setState(() {
          primaryTC = TabController(length: _tabList?.length ?? 0, vsync: this);
          primaryTC.addListener(() {
            if (primaryTC.index.toDouble() == primaryTC.animation.value) {
              print(primaryTC.index);
              if (mounted) {
                setState(() {
                  indicatorIndex = primaryTC.index;
                });
              }
            }
          });
        });
      }
    });
  }

  Future<void> method() async {
    DateTime dateTime = DateTime.now();

    int hour = dateTime.hour % 2 > 0
        ? ((dateTime.hour >= 1 ? dateTime.hour : 0) - 1)
        : dateTime.hour;

    int now = hour;

    if (hour >= 16) {
      hour = hour - 2 * ((hour - 16) ~/ 2);
    }
    await Future.delayed(Duration(seconds: 2), () {
      _tabList = [
        Tab(
            child: Column(children: [
          Text(
            hour.toString() + ':00',
            style: TextStyle(
                fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold),
          ),
          Text(_textState(now, hour),
              style: TextStyle(
                  fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ])),
        Tab(
            child: Column(children: [
          Text(
            (hour + 2).toString() + ':00',
            style: TextStyle(
                fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold),
          ),
          Text(_textState(now, hour + 2),
              style: TextStyle(
                  fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ])),
        Tab(
            child: Column(children: [
          Text(
            (hour + 4).toString() + ':00',
            style: TextStyle(
                fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold),
          ),
          Text(_textState(now, hour + 4),
              style: TextStyle(
                  fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ])),
        Tab(
            child: Column(children: [
          Text(
            (hour + 6).toString() + ':00',
            style: TextStyle(
                fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold),
          ),
          Text(_textState(now, hour + 6),
              style: TextStyle(
                  fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ])),
      ];
    });
  }

  String _textState(int now, int hour) {
    return now > hour ? '已经结束' : ((now - hour).abs() > 1 ? '即将开始' : '正在秒杀');
  }

  @override
  void dispose() {
    primaryTC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(750, 1334),
        orientation: Orientation.portrait);
    return Scaffold(
        appBar: YPNavigationBar('秒杀活动',
            showLine: false,
            backgroundColor: EsColors.Primary,
            backBtnColor: EsColors.White,
            titleColor: EsColors.White),
        body: _buildScaffoldBody());
  }

  Widget _buildScaffoldBody() {
    return ExtendedNestedScrollView(
      headerSliverBuilder: (BuildContext c, bool f) {
        return <Widget>[
          SliverToBoxAdapter(child: _header()),
          SliverToBoxAdapter(child: _adbox()),
        ];
      },
      pinnedHeaderSliverHeightBuilder: () => 0,
      onlyOneScrollInBody: false,
      body: TabBarView(
          controller: primaryTC,
          children: List<Widget>.generate(
              primaryTC?.length ?? 0, (int index) => _infoList(index))),
    );
  }

  Widget _header() {
    return Container(
      color: EsColors.Primary,
      child: TabBar(
        controller: primaryTC,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.White,
        isScrollable: false,
        unselectedLabelColor: EsColors.Fill,
        indicatorSize: TabBarIndicatorSize.label,
        indicatorWeight: 0,
        indicator: const ExtendedUnderlineTabIndicator(
            borderSide: BorderSide(color: EsColors.Primary, width: 0)),
        tabs: List<Widget>.generate(
            _tabList?.length ?? 0,
            (int index) => Stack(
                  children: [
                    SizedBox(width: MediaQuery.of(context).size.width / 4),
                    Positioned(
                        bottom: 18.w,
                        left: 28.w,
                        right: 28.w,
                        child: Container(
                          height: 36.w,
                          decoration: BoxDecoration(
                              color: indicatorIndex == index
                                  ? EsColors.White.withOpacity(0.5)
                                  : EsColors.Primary,
                              borderRadius: BorderRadius.circular(16.w)),
                        )),
                    Positioned(
                        child: Row(
                      children: [
                        Container(
                            width: MediaQuery.of(context).size.width / 4 - 3,
                            child: Center(child: _tabList[index])),
                        Container(
                            color: EsColors.Fill.withOpacity(0.5),
                            width: index + 1 == (_tabList?.length ?? 0) ? 0 : 1,
                            height: 40.w)
                      ],
                    ))
                  ],
                )),
      ),
    );
  }

  /// 广告位
  Widget _adbox() {
    return Stack(children: [
      SizedBox(
        height: 140,
        width: double.infinity,
      ),
      Positioned(
        child: Container(
          height: 20,
          width: double.infinity,
          child: Container(
              decoration: BoxDecoration(
                  color: EsColors.Primary,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(30),
                      bottomRight: Radius.circular(30)))),
        ),
      ),
      Positioned(
        child: AdBox(
          aspectRatio: 355 / 145,
          adKey: 'Adv',
          height: 145,
          borderRadius: 6,
          margin: EdgeInsets.fromLTRB(12.0, 4, 12.0, 0),
        ),
      )
    ]);
  }

  /// 下边对应的列表
  Widget _infoList(int index) {
    return ListView.builder(
        itemBuilder: (context, index) {
          return _item(index);
        },
        itemCount: 20);
  }

  Widget _item(int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(20.w, 26.w, 20.w, 0),
      padding: EdgeInsets.all(20.w),
      decoration: EsDecoration.BoxShadowWithRadius,
      alignment: Alignment.center,
      child: Row(
        children: [
          CachedImage(
              width: 260.w,
              height: 260.w,
              path:
                  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.biaobaiju.com%2Fuploads%2F20190903%2F13%2F1567488509-nBLvqRfjrc.jpg&refer=http%3A%2F%2Fimage.biaobaiju.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633718640&t=65f1224b3ef6a31c77988153388af5d7'),
          SizedBox(width: 24.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                    constraints: BoxConstraints(minHeight: 140.w),
                    child: Text('Nature Republic自然共和国原自然乐园芦荟胶补水面霜面膜300ml',
                        style: TextStyle(
                            color: EsColors.Title,
                            fontSize: EsSizes.SM * 2.sp,
                            fontWeight: EsFontWeights.Normal))),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text('已抢98765件',
                            style: TextStyle(
                                color: EsColors.ContentSecondary,
                                fontSize: EsSizes.XS * 2.sp,
                                fontWeight: EsFontWeights.Normal)),
                        Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 4.w, right: 10.w),
                              child: Text('￥189',
                                  style: TextStyle(
                                      color: EsColors.Primary,
                                      fontSize: EsSizes.XL * 2.sp,
                                      fontWeight: EsFontWeights.Normal)),
                            ),
                            Text('￥300',
                                style: TextStyle(
                                    decoration: TextDecoration.lineThrough,
                                    color: EsColors.ContentSecondary,
                                    fontSize: EsSizes.XS * 2.sp,
                                    fontWeight: EsFontWeights.Normal)),
                          ],
                        ),
                      ],
                    ),
                    Expanded(child: SizedBox()),
                    GestureDetector(
                      onTap: () {
                        print('马上抢');
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 10.w, horizontal: 24.w),
                        child: Text('马上抢',
                            style: TextStyle(
                                color: EsColors.White,
                                fontSize: EsSizes.MD * 2.sp,
                                fontWeight: EsFontWeights.Medium)),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            ///渐变色
                            colors: [Color(0xffea5504), Color(0xffffbd00)],
                          ),
                          borderRadius: BorderRadius.all(Radius.circular(30.w)),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }


}
